﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using Microsoft.Phone.Tasks;

namespace BuyTrainTicket
{
    public partial class QueryOrder : PhoneApplicationPage
    {
        private string username;
        private string password;
        private string key;

        public QueryOrder()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string msgJson = "";
            if (NavigationContext.QueryString.TryGetValue("msgJson", out msgJson))
            {
                JObject respJObject = JsonConvert.DeserializeObject<JObject>(msgJson);
                JToken isSuccess = respJObject.GetValue("isSuccess");
                if ((bool)isSuccess == true)
                {
                    key = (string)respJObject.GetValue("key");
                    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
                    settings.TryGetValue<String>("username", out username);
                    settings.TryGetValue<String>("password", out password);
                    if (username == null || password == null)
                    {
                        MessageBox.Show("请先设置用户名和密码");
                        NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                        return;
                    }
                    sendRequest(Util.host + "/servlet/Buy12306Servlet?action=getresponse&password=" + password + "&username=" + username + "&type==getresponse&version=8.1");


                }
            }
        }

        void sendRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                StringBuilder postData = new StringBuilder();
                postData.Append("key=" + key);

                byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    if ((bool)responseObj.GetValue("isSuccess") == true)
                    {
                        JToken respHtml = responseObj.GetValue("respHtml");

                        Dispatcher.BeginInvoke(() =>
                        {
                            webbrowser.NavigateToString((string)respHtml);
                        });
                    }
                    else
                    {
                        string errMsg = (string)responseObj.GetValue("errMsg");
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(errMsg);
                        });
                    }
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                           {
                               MessageBox.Show(response.StatusCode.ToString());
                           });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }

        }

        private void Button_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask();
            task.Uri = new Uri("https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y");
            task.Show();
        }

    }
}